/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.DatatypeConverter;
import org.jdom.Element;
import models.PersonalData;
import utils.SignRequest;

/**
 *
 * @author Maciek
 */
public class SignCertificate {
    
    
    
    
    static private String bytesToString(byte[] bytes){
        return DatatypeConverter.printBase64Binary(bytes);
    }
    
    static private byte[] stringToBytes(String string){
        return DatatypeConverter.parseBase64Binary(string);
    } 
    
    static private void writeCSR(PersonalData pd, byte[] pkcs10) throws FileNotFoundException, IOException{
            FileOutputStream fileOutputStream = new FileOutputStream(PathCreator.path(pd) + ".csr");
            PrintStream ps = new PrintStream(fileOutputStream);
            ps.write(pkcs10);
            fileOutputStream.close();
    }
    
    
    static public int dealWithSignReq(Element sigrec, PersonalData pd, String password){
        System.out.println("Teraz spróbuje wypisać PKCS10");
         try{
            String helpString = sigrec.getValue();
            byte[] pkcs10  = stringToBytes(helpString);
            writeCSR(pd,pkcs10); 
            SubjectNameFromCsr snfcsr = new SubjectNameFromCsr();
            int retVal = snfcsr.checkPersonalDataInCSR(pd);
            if(retVal!=0) return retVal;
            else return  SignRequest.signRequest(pd, password);
            
        } catch (InterruptedException ex) {
            Logger.getLogger( SignCertificate.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger( SignCertificate .class.getName()).log(Level.SEVERE, null, ex);
        } 
         return -1;
    }
}
